package spring.chatroom.java_chatroom.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import spring.chatroom.java_chatroom.common.constant.Constants;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //默认过期时间
    private final Long HOURS = 12L;

    public String set(String key, String value) {
        if (key == null || value == null) {
            return "k v 不能为空";
        }

        try {
            stringRedisTemplate.opsForValue().set(key, value, HOURS, TimeUnit.HOURS);
        } catch (Exception e) {
            log.error("储存到redis中发送了错误: {}", e.getMessage(), e);
            return Constants.REDIS_ERROR;
        }
        return null;
    }

    public String set(String key, String value, Long seconds) {
        if (key == null || value == null) {
            return "k v 不能为空";
        }

        try {
            stringRedisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("储存到redis中发送了错误: {}", e.getMessage(), e);
            return Constants.REDIS_ERROR;
        }
        return null;
    }

    public String getAndExpire(String key) {
        if (key == null) {
            return null;
        }
        try {
            return stringRedisTemplate.opsForValue().getAndExpire(key, HOURS, TimeUnit.HOURS);
        } catch (Exception e) {
            log.error("从redis中获取值错误: {}", e.getMessage(), e);
            return Constants.REDIS_ERROR;
        }
    }

    public String get(String key) {
        if (key == null) {
            return null;
        }

        try {
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("从redis中获取值错误: {}", e.getMessage(), e);
            return Constants.REDIS_ERROR;
        }
    }

    public void remove(String s) {
        if (s == null) {
            return;
        }

        try {
            stringRedisTemplate.delete(s);
        } catch (Exception e) {
            log.error("从redis中删除值错误: {}", e.getMessage(), e);
        }
    }
}
